package cn.tjad.tjad2.module.design.designDetail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.net.http.HttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.CommonEntity;
import cn.tjad.tjad2.data.bean.DesignDetail;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.module.user.userselect.SelectMode;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import cn.tjad.tjad2.module.common.pictureselect.PictureSelectWidget;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

public class DesignHandleView extends FrameLayout implements AdapterView.OnItemSelectedListener {

    @BindView(R.id.design_detail_handle_picture_select)
    PictureSelectWidget pictureSelectWidget;
    @BindView(R.id.design_handle_member_list)
    MemberListView memberListView;
    @BindView(R.id.design_detail_handle_spinner)
    Spinner handleSpinner;
    @BindView(R.id.design_detail_handle_content_tip)
    TextView handleContentTip;
    @BindView(R.id.design_detail_invite_layout)
    View inviteLayout;
    @BindView(R.id.design_handle_invite_divideline)
    View divideLine;
    @BindView(R.id.design_detail_handle_content)
    EditText contentET;

    private CompositeDisposable compositeDisposable;
    private Gson gson = new Gson();
    private DesignDetail designDetail;
    private Handler eventHandler;

    public DesignHandleView( @NonNull Context context) {
        this(context, null);
    }

    public DesignHandleView( @NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.design_detail_handle, this);
        ButterKnife.bind(this);
        handleSpinner.setOnItemSelectedListener(this);
    }

    public void setCompositeDisposable(CompositeDisposable compositeDisposable) {
        this.compositeDisposable = compositeDisposable;
    }

    public void setEventHandler(Handler eventHandler) {
        this.eventHandler = eventHandler;
    }

    public void setData(DesignDetail designDetail) {
        this.designDetail = designDetail;
        if (designDetail == null) {
            User createUser = designDetail.createUser;
            int myId = TjadApplication.getInstance().getSession().getLoginInfo().id;
            if (myId != createUser.id) {
                handleSpinner.setSelection(0);
                handleSpinner.setEnabled(false);
            } else {
                handleSpinner.setEnabled(true);
            }
        }
    }

    @OnClick({R.id.design_detail_invite_layout, R.id.design_detail_sumbit_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.design_detail_invite_layout:
                SelectMode.setSelectMode(SelectMode.MULTIPLE_CHOICE);
                RouteUtils.toPageForResult((Activity) getContext(), PageId.USER_SELECT_2, null, 1006);
            break;
            case R.id.design_detail_sumbit_btn:
                onSubmit();
                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            handleContentTip.setText("回复内容");
            inviteLayout.setVisibility(VISIBLE);
            divideLine.setVisibility(VISIBLE);
        } else if (position == 1) {
            handleContentTip.setText("解决方案");
            inviteLayout.setVisibility(GONE);
            divideLine.setVisibility(GONE);
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        pictureSelectWidget.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1006 && resultCode == Activity.RESULT_OK) {
            ArrayList<User> selectedUsers = (ArrayList<User>) data.getSerializableExtra(Keys.SELECTED_RESULTS);
            memberListView.setData(selectedUsers);
        }
    }

    private void onSubmit() {
        int select = handleSpinner.getSelectedItemPosition();
        if (select == 0) {
            userBeanConvert();
        } else if (select == 1) {
            submitDesign();
        }
    }

    private void userBeanConvert() {
        ProgressDialogUtils.show(getContext());
        List<User> users = memberListView.getData();
        List<CommonEntity> userEntityList = new ArrayList<>();
        if (users != null || users.size() > 0) {
            Observable.fromIterable(users)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(user -> {
                        CommonEntity entity = new CommonEntity();
                        entity.id = user.id;
                        entity.name = user.name;
                        return entity;
                    }).doOnNext(commonEntity -> userEntityList.add(commonEntity))
                    .doOnComplete(() -> {
                        reply(userEntityList);
                    }).subscribe();

        } else {
            reply(null);
        }
    }

    private void reply(final List<CommonEntity> userList) {
        pictureSelectWidget.uploadPictures(new PictureSelectWidget.IPictureUploadCallback() {
            @Override
            public void onError(String errorMsg) {
                Tools.showToast(errorMsg);
            }

            @Override
            public void onSuccess(List<String> urlList) {
                replyDesign( designDetail.id, urlList, contentET.getText().toString().trim(), userList);
            }
        });
    }

    private void submitDesign() {
        ProgressDialogUtils.show(getContext());
        pictureSelectWidget.uploadPictures(new PictureSelectWidget.IPictureUploadCallback() {
            @Override
            public void onError(String errorMsg) {
                Tools.showToast(errorMsg);
            }

            @Override
            public void onSuccess(List<String> urlList) {
                finishDesign(designDetail.id, urlList, contentET.getText().toString().trim());
            }
        });
    }

    //格式如下
    //{"photos":["http://bim.tjad.cn/image/2019/4/1555240436139635.png","http://bim.tjad.cn/image/2019/4/1555240444308603.png"],"content":"dffsfdgdfg","relateUsers":[{"id":2,"name":"徐斌","avatar":"http://bim.tjad.cn/image/2018/5/152532485859793.png"},{"id":15,"name":"陈岱维"},{"id":109,"name":"孙亦尧"}]}
    private void replyDesign(int designId, List<String> photos, String content, List<CommonEntity> relatedUsers) {
        JsonObject json = new JsonObject();
        if (photos != null && photos.size() > 0) {
            JsonArray photoJson = (JsonArray) gson.toJsonTree(photos);
            json.add("photos", photoJson);
        }
        json.addProperty("content", content);
        if (relatedUsers != null && relatedUsers.size() > 0) {
            JsonArray userJson = (JsonArray) gson.toJsonTree(relatedUsers);
            json.add("relateUsers", userJson);
        }
        RequestBody body = RequestBody.create(HttpUtils.JSON, gson.toJson(json));
        RetrofitManager.getInstance().getApiService()
                .replyDesign(Tools.getProjectId(), designId, body)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<String>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<String> t) {
                        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                        builder.setTitle("提示")
                                .setMessage("该问题销项已回复")
                                .setPositiveButton("确认", new OnDialogClickListener() {
                                    @Override
                                    public boolean onClick(Dialog dialog, int which) {
                                        requestDesignDetail();
                                        resetUI();
                                        ProgressDialogUtils.dismiss();
                                        return true;
                                    }
                                }).show(getSupportFragmentManager());
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        ProgressDialogUtils.dismiss();
                    }
                });
    }

    private void requestDesignDetail() {
        eventHandler.sendEmptyMessage(1);
    }

    private void resetUI() {
        handleSpinner.setSelection(0);
        contentET.setText("");
        memberListView.setData(null);
        pictureSelectWidget.clear();
    }

    //格式
    //{"finishPhotos":["http://bim.tjad.cn/image/2019/4/1555241598568605.png"],"finishContent":"chhvhhvhhrjjfjjjjg"}
    public void finishDesign(int designId, List<String> photos, String content) {
        JsonObject json = new JsonObject();
        if (photos != null && photos.size() > 0) {
            JsonArray photoJson = (JsonArray) gson.toJsonTree(photos);
            json.add("finishPhotos", photoJson);
        }
        json.addProperty("finishContent", content);
        RequestBody body = RequestBody.create(HttpUtils.JSON, gson.toJson(json));
        RetrofitManager.getInstance().getApiService()
                .finishDesign(Tools.getProjectId(), designId, body)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<String>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<String> t) {
                        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                        builder.setTitle("提示")
                                .setMessage("该问题销项已完成")
                                .setPositiveButton("确认", new OnDialogClickListener() {
                                    @Override
                                    public boolean onClick(Dialog dialog, int which) {
                                        requestDesignDetail();
                                        resetUI();
                                        ProgressDialogUtils.dismiss();
                                        return true;
                                    }
                                }).show(getSupportFragmentManager());
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        ProgressDialogUtils.dismiss();
                    }
                });
    }

    FragmentManager getSupportFragmentManager() {
        return ((FragmentActivity)getContext()).getSupportFragmentManager();
    }

}
